﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using AppAcc.Models;
using AppAcc.Views.DanhMuc;

namespace AppAcc.Views.KTVTCCDC
{
    public partial class FormChungTuXuatKhoHangThemMoi : DevComponents.DotNetBar.RibbonForm
    {
        public FormChungTuXuatKhoHangThemMoi()
        {
            InitializeComponent();
        }
        //private AppAccContext db = new AppAccContext();
        private PhanMenKeToanEntities1 db = new PhanMenKeToanEntities1();
        private int indexrow = 0;
        #region Event
        private void FormChungTuXuatKhoHangThemMoi_Load(object sender, EventArgs e)
        {
            Reset();
        }
        private void bttThemMoi_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void bttLuu_Click(object sender, EventArgs e)
        {
            Create();
        }

        private void bttLuu_Thoat_Click(object sender, EventArgs e)
        {
            Create();
            this.Close();
        }

        private void bttLuu_ThemMoi_Click(object sender, EventArgs e)
        {
            Create();
            Reset();
        }

        private void bttInChungTu_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Chua code!");
        }

        private void bttThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbbNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void cbbNhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void txtNoiDung_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void dtiNgayChungTu_Click(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void dtiNgayLapPhieu_ValueChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void dtiNgayChungTu_ValueChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void bttThemMoiNhaCungCap_Click(object sender, EventArgs e)
        {
            var f = new FormDoiTac();
            f.ShowDialog();
        }

        private void bttThemMoiNhanVien_Click(object sender, EventArgs e)
        {
            var f = new FormNhanVien();
            f.ShowDialog();
        }

        private void dgvChiTietChungTu_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right) return;
            var ht = dgvChiTietChungTu.HitTest(e.X, e.Y);
            var rowindex = ht.RowIndex;
            indexrow = rowindex;
            if (ht.ColumnIndex != -1 && ht.RowIndex != -1)
            {
                var Menu = new ContextMenuStrip();
                var chen = new ToolStripMenuItem("Chèn (Ins)");//new button
                chen.MouseDown += new MouseEventHandler(CmsChenDong_Click);// add event to button
                var xoa = new ToolStripMenuItem("Xóa (Del)");
                xoa.MouseDown += new MouseEventHandler(CmsXoaDong_Click);
                Menu.Items.AddRange(new ToolStripItem[] { chen });//add button to menu strip
                Menu.Items.AddRange(new ToolStripItem[] { xoa });
                dgvChiTietChungTu.ContextMenuStrip = Menu;
            }
            else
                dgvChiTietChungTu.ContextMenuStrip = null;
        }
        private void CmsChenDong_Click(object sender, EventArgs e)
        {
            var dgwr = new DataGridViewRow();
            dgvChiTietChungTu.Rows.Insert(indexrow, dgwr);
        }
        private void CmsXoaDong_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in dgvChiTietChungTu.Rows)
            {
                if (!r.IsNewRow)
                {
                    dgvChiTietChungTu.Rows.RemoveAt(r.Index);
                }
            }
        }
        private void dgvChiTietChungTu_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            KiemTra();
            UpdateAmount(e.ColumnIndex);
        }

        private void cbbNhomNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            var index = Convert.ToInt32(cbbNhomNhaCungCap.SelectedIndex);
            if (index < 1) return;
            var id = Convert.ToInt32(cbbNhomNhaCungCap.SelectedValue);
            cbbNhaCungCap.DataSource = db.DoiTacs.Where(t => t.NhomDoiTacId == id).ToList();
            cbbNhaCungCap.DisplayMember = "TenDoiTac";
            cbbNhaCungCap.ValueMember = "Id";
            cbbNhaCungCap.SelectedIndex = -1;
            cbbNhaCungCap.Enabled = true;
        }

        #endregion Event
        #region Metho
        void GetMaChungTu()
        {
            txtSoChungTu.Text = "PXK" + (db.ChungTus.Count(t => t.TrangThai == 2) + 1).ToString();
            dtiNgayChungTu.Value = DateTime.Now;
            dtiNgayLapPhieu.Value = DateTime.Now;
        }
        void FillDataChungTu()
        {
            cbbNhanVien.DataSource = db.NhanViens.ToList();
            cbbNhanVien.DisplayMember = "TenNhanVien";
            cbbNhanVien.ValueMember = "Id";

            cbbNhomNhaCungCap.DataSource = db.NhomDoiTacs.ToList();
            cbbNhomNhaCungCap.DisplayMember = "TenNhomDoiTac";
            cbbNhomNhaCungCap.ValueMember = "Id";
            cbbNhomNhaCungCap.SelectedIndex = 0;

            cbbNhaCungCap.Enabled = false;
        }
        void KiemTra()
        {
            if (txtNoiDung.Text != "" && Convert.ToInt32(cbbNhaCungCap.SelectedValue) != 0 && Convert.ToInt32(cbbNhanVien.SelectedValue) != 0 && dgvChiTietChungTu.RowCount > 1)//&& dtiNgayChungTu.Value.ToString().Length > 0 && dtiNgayLapPhieu.Value.ToString().Length > 0
            {
                bttInChungTu.Enabled = true;
                bttLuu.Enabled = true;
                bttLuu_ThemMoi.Enabled = true;
                bttLuu_Thoat.Enabled = true;
            }
            else
            {
                bttInChungTu.Enabled = false;
                bttLuu.Enabled = false;
                bttLuu_ThemMoi.Enabled = false;
                bttLuu_Thoat.Enabled = false;
            }
        }

        void FillCbbDataDgv()
        {
            var nn = dgvChiTietChungTu.Columns["TaiKhoanNo"] as DataGridViewComboBoxColumn;
            if (nn != null)
            {
                nn.DataSource = db.TaiKhoans.ToList();
                nn.DisplayMember = "Id";
                nn.ValueMember = "Id";
            }

            var c = dgvChiTietChungTu.Columns["TaiKhoanCo"] as DataGridViewComboBoxColumn;
            if (c != null)
            {
                c.DataSource = db.TaiKhoans.ToList();
                c.DisplayMember = "Id";
                c.ValueMember = "Id";
            }

            var n = dgvChiTietChungTu.Columns["NhomThueHangHoaId"] as DataGridViewComboBoxColumn;
            if (n != null)
            {
                n.DataSource = db.NhomThueHangHoas.Where(t => t.LoaiThue == 2).ToList();
                n.DisplayMember = "TenThue";
                n.ValueMember = "Id";
            }

            var n1 = dgvChiTietChungTu.Columns["HangHoaId"] as DataGridViewComboBoxColumn;
            if (n1 != null)
            {
                n1.DataSource = db.HangHoas.ToList();
                n1.DisplayMember = "TenHangHoa";
                n1.ValueMember = "Id";
            }

            var n2 = dgvChiTietChungTu.Columns["KhoHangId"] as DataGridViewComboBoxColumn;
            if (n2 == null) return;
            n2.DataSource = db.KhoHangs.ToList();
            n2.DisplayMember = "TenKhoHang";
            n2.ValueMember = "Id";
        }
        void Create()
        {
            var pt = new ChungTu();
            pt.Id = txtSoChungTu.Text;
            pt.NgayChungTu = dtiNgayChungTu.Value;
            pt.SoChungTuGoc = txtSoChungTuGoc.Text;
            pt.NgayLapPhieu = dtiNgayLapPhieu.Value;
            pt.NhanVienId = Convert.ToInt32(cbbNhanVien.SelectedValue);
            pt.DoiTacId = Convert.ToInt32(cbbNhaCungCap.SelectedValue);
            pt.NoiDung = txtNoiDung.Text;
            pt.TrangThai = 2;
            int co = 1;
            decimal soTienNo = 0;
            decimal soTienCo = 0;
            pt.TongTien = 0;
            var kt = true;
            foreach (DataGridViewRow item in dgvChiTietChungTu.Rows)
            {
                if (co >= dgvChiTietChungTu.RowCount) continue;
                var ct = new ChungTuChiTiet();
                int sl = 0;
                decimal gianew = 0;
                ct.ChungTuId = pt.Id;
                if (item.Cells["TaiKhoanNo"].Value != null && item.Cells["TaiKhoanNo"].Value.ToString().Length > 0)
                {
                    ct.TaiKhoanNo = item.Cells["TaiKhoanNo"].Value.ToString();
                }
                else if (item.Cells["TaiKhoanCo"].Value != null && item.Cells["TaiKhoanCo"].Value.ToString().Length > 0)
                {
                    ct.TaiKhoanCo = item.Cells["TaiKhoanCo"].Value.ToString();
                }
                if (item.Cells["HangHoaId"].Value != null && item.Cells["HangHoaId"].Value.ToString().Length > 0)
                {
                    ct.HangHoaId = Convert.ToInt32(item.Cells["HangHoaId"].Value);
                }
                else
                {
                    ct.HangHoaId = null;
                }
                if (item.Cells["SoLuong"].Value != null && item.Cells["SoLuong"].Value.ToString().Length > 0)
                {
                    ct.SoLuong = Convert.ToInt32(item.Cells["SoLuong"].Value);
                    sl = Convert.ToInt32(item.Cells["SoLuong"].Value);
                }
                else
                {
                    ct.SoLuong = null;
                }
                if (item.Cells["GiaGoc"].Value != null && item.Cells["GiaGoc"].Value.ToString().Length > 0)
                {
                    ct.GiaNhap = Convert.ToInt32(item.Cells["GiaGoc"].Value);
                    gianew = Convert.ToInt32(item.Cells["GiaGoc"].Value);
                }
                else
                {
                    ct.GiaNhap = null;
                }
                if (item.Cells["GiaXuat"].Value != null && item.Cells["GiaXuat"].Value.ToString().Length > 0)
                {
                    ct.GiaXuat = Convert.ToInt32(item.Cells["GiaXuat"].Value);
                    gianew = Convert.ToInt32(item.Cells["GiaXuat"].Value);
                }
                else
                {
                    ct.GiaXuat = null;
                }
                if (item.Cells["SoTien"].Value != null && item.Cells["SoTien"].Value.ToString().Length > 0)
                {
                    ct.SoTien = Convert.ToDecimal(item.Cells["SoTien"].Value);
                }
                else
                {
                    MessageBox.Show("Dự liệu không hợp lệ!");
                    kt = false;
                }
                if (item.Cells["KhoHangId"].Value != null && item.Cells["KhoHangId"].Value.ToString().Length > 0)
                {
                    ct.KhoHangId = Convert.ToInt32(item.Cells["KhoHangId"].Value);
                }
                else
                {
                    ct.KhoHangId = null;
                }
                if (item.Cells["NhomThueHangHoaId"].Value != null && item.Cells["NhomThueHangHoaId"].Value.ToString().Length > 0)
                {
                    ct.NhomThueHangHoaId = Convert.ToInt32(item.Cells["NhomThueHangHoaId"].Value);
                }
                else
                {
                    ct.NhomThueHangHoaId = null;
                }
                if (item.Cells["DienGiai"].Value != null && item.Cells["DienGiai"].Value.ToString().Length > 0)
                {
                    ct.DienGiai = item.Cells["DienGiai"].Value.ToString();
                }
                else
                {
                    ct.DienGiai = null;
                }
                if (ct.TaiKhoanNo != null)
                {
                    soTienNo += Convert.ToDecimal(ct.SoTien);
                }
                else if (ct.TaiKhoanCo != null)
                {
                    soTienCo += Convert.ToDecimal(ct.SoTien);
                }

                if (ct.HangHoaId != null)
                {
                    var h = db.HangHoas.Find(ct.HangHoaId);
                    h.SoLuong = h.SoLuong - ct.SoLuong;
                    db.Entry(h).State = EntityState.Modified;
                }
                co++;
                db.ChungTuChiTiets.Add(ct);
            }
            pt.TongTien += soTienCo;
            if (soTienCo != soTienNo)
            {
                MessageBox.Show("Số phát sinh Nợ phải bằng số phát sinh Có.");
                kt = false;
            }
            db.ChungTus.Add(pt);
            if (kt == true)
            {
                try
                {
                    db.SaveChanges();
                    MessageBox.Show("Thêm mới thành công!");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        void Reset()
        {
            txtNoiDung.Text = "";
            txtSoChungTuGoc.Text = "";
            GetMaChungTu();
            FillDataChungTu();
            FillCbbDataDgv();
            cbbNhaCungCap.SelectedIndex = -1;
            cbbNhanVien.SelectedIndex = -1;
            if (dgvChiTietChungTu.DataSource != null)
            {
                dgvChiTietChungTu.DataSource = null;
            }
            else
            {
                dgvChiTietChungTu.Rows.Clear();
            }
            KiemTra();
        }
        private void UpdateAmount(int index)
        {
            int counter;
            for (counter = 0; counter < (dgvChiTietChungTu.Rows.Count - 1); counter++)
            {
                if (dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanNo"].Value == null &&
                    dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanCo"].Value == null) continue;
                var tkNo = Convert.ToInt32(dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanNo"].Value);
                var tkCo = Convert.ToInt32(dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanCo"].Value);

                if (tkNo > 0 && tkCo > 0)
                {
                    if (index == 0)
                    {
                        MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                        dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanNo"].Value = null;
                    }
                    else if (index == 1)
                    {
                        MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                        dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanCo"].Value = null;
                    }
                }
                else
                {
                    if (tkNo > 150 && tkNo < 160 || tkCo > 150 && tkCo < 160 || tkNo == 1561 || tkNo == 1567 || tkCo == 1561 || tkCo == 1567)
                    {
                        dgvChiTietChungTu.Rows[counter].Cells["HangHoaId"].ReadOnly = false;
                        dgvChiTietChungTu.Rows[counter].Cells["SoLuong"].ReadOnly = false;
                        dgvChiTietChungTu.Rows[counter].Cells["GiaXuat"].ReadOnly = false;
                        dgvChiTietChungTu.Rows[counter].Cells["KhoHangId"].ReadOnly = false;
                        dgvChiTietChungTu.Rows[counter].Cells["SoTien"].ReadOnly = false;
                    }
                    else
                    {
                        dgvChiTietChungTu.Rows[counter].Cells["HangHoaId"].ReadOnly = true;
                        dgvChiTietChungTu.Rows[counter].Cells["SoLuong"].ReadOnly = true;
                        dgvChiTietChungTu.Rows[counter].Cells["GiaXuat"].ReadOnly = true;
                        dgvChiTietChungTu.Rows[counter].Cells["KhoHangId"].ReadOnly = true;
                    }
                    if (tkNo == 133 || tkNo == 1331 || tkNo == 1332 || tkCo == 133 || tkCo == 1331 || tkCo == 1332 || tkCo == 621 || tkNo == 621)
                    {
                        dgvChiTietChungTu.Rows[counter].Cells["NhomThueHangHoaId"].ReadOnly = false;
                        dgvChiTietChungTu.Rows[counter].Cells["SoTien"].ReadOnly = false;
                    }
                    else
                    {
                        dgvChiTietChungTu.Rows[counter].Cells["NhomThueHangHoaId"].ReadOnly = true;
                    }
                    // load gia von tham khao
                    if (dgvChiTietChungTu.Rows[counter].Cells["HangHoaId"].Value != null && index == 2)
                    {
                        if (dgvChiTietChungTu.Rows[counter].Cells["HangHoaId"].Value.ToString().Length != 0)
                        {
                            int id = Convert.ToInt32(dgvChiTietChungTu.Rows[counter].Cells["HangHoaId"].Value.ToString());
                            var h = db.HangHoas.Find(id);
                            dgvChiTietChungTu.Rows[counter].Cells["GiaGoc"].Value = h.GiaBQGQ.ToString();
                        }
                    }
                    decimal soluong = 0;
                    decimal gia = 0;
                    if (index == 3 || index == 5)
                    {
                        if (dgvChiTietChungTu.Rows[counter].Cells["SoLuong"].Value == null ||
                        dgvChiTietChungTu.Rows[counter].Cells["GiaXuat"].Value == null) continue;
                        if (dgvChiTietChungTu.Rows[counter].Cells["SoLuong"].Value.ToString().Length != 0)
                        {
                            soluong = Convert.ToDecimal(dgvChiTietChungTu.Rows[counter].Cells["SoLuong"].Value.ToString());
                        }

                        if (dgvChiTietChungTu.Rows[counter].Cells["GiaXuat"].Value.ToString().Length != 0)
                        {
                            gia = Convert.ToDecimal(dgvChiTietChungTu.Rows[counter].Cells["GiaXuat"].Value.ToString());
                        }
                        dgvChiTietChungTu.Rows[counter].Cells["SoTien"].Value = (soluong * gia).ToString();
                    }
                }
            }
        }
        #endregion Metho
    }
}